package changgou.oauth.service.impl;

import changgou.oauth.service.OauthHeadService;
import changgou.oauth.util.AuthToken;
import changgou.oauth.util.ServiceStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.Base64;
import java.util.Map;

/**
 * 版权：(C) 版权所有 2000-2020 上海天好电子商务有限公司苏州分公司
 * <简述>
 * <详细描述>
 *
 * @author LiuShanshan
 * @version $Id$
 */
public class OauthHeadServiceImpl implements OauthHeadService{
    @Autowired
    public RestTemplate restTemplate;

    @Autowired
    public LoadBalancerClient loadBalancerClient;

    @Override
    public AuthToken getTokeToAuthToken(String username, String password, String clientId, String clientSecret, String grandType) {
        // 定义url
        URI uri = loadBalancerClient.choose(ServiceStatus.OAUTH_STATUS).getUri();
        //2.定义头信息 (有client id 和client secr)
        MultiValueMap<String,String> headers = new LinkedMultiValueMap<>();
        headers.add("Authorization","Basic "+ Base64.getEncoder().encodeToString(new String(clientId+":"+clientSecret).getBytes()));
        //3. 定义请求体  有授权模式 用户的名称 和密码
        MultiValueMap<String,String> formData = new LinkedMultiValueMap<>();
        formData.add("grant_type",grandType);
        formData.add("username",username);
        formData.add("password",password);

        /**
         * 参数1  指定要发送的请求的url
         * 参数2  指定要发送的请求的方法 PSOT
         * 参数3 指定请求实体(包含头和请求体数据)
         */
        HttpEntity<MultiValueMap> requestentity = new HttpEntity<MultiValueMap>(formData,headers);
//        URI url,        跳转的地址
//        HttpMethod method,
//        @Nullable HttpEntity<?> requestEntity,
//        Class<T> responseType
        ResponseEntity<Map> exchange = restTemplate.exchange(uri, HttpMethod.POST, requestentity, Map.class);
        Map body = exchange.getBody();
        AuthToken authToken = new AuthToken();
        authToken.setAccessToken((String )body.get("access_token"));
        return null;
    }
}
